package exclude

import (
	"errors"
	"regexp"
	"sieve_admin_server_userpass/lib/mysql"
	"strings"

	"sieve_admin_server_userpass/app/server"
	_ "sieve_admin_server_userpass/im3/app/syncMembers"
	// "database/sql"
)

type DB struct {
	AdminDB *mysql.DB
	NewAdDB *mysql.DB
}

func (d *DB) GetUserInfo(uid int) (map[string]interface{}, error) {
	var (
		Name string
	)
	if err := d.AdminDB.QueryRow("SELECT `areaName` FROM `im_allUser` WHERE `Uid`=?", uid).Scan(&Name); err != nil {
		return nil, err
	}
	leader := 0
	role := "超级管理员"
	if uInfo := server.GetUserInfo(uid); uInfo != nil {
		leader = uInfo.Leader
		reg := regexp.MustCompile(`\(.*\)|（.*）`)
		role = reg.ReplaceAllString(uInfo.Title, "")
	}
	var ret = map[string]interface{}{
		"uid":    uid,
		"name":   Name,
		"leader": leader,
		"role":   role,
	}
	return ret, nil
}

func (d *DB) GetAllUser() []*BaseName {
	var sql = "SELECT Uid,`areaName` from im_allUser"
	rows, err := d.AdminDB.Query(sql)
	if err != nil {
		return nil
	}
	defer rows.Close()
	list := []*BaseName{}
	for rows.Next() {
		info := &BaseName{}
		err := rows.Scan(&info.Id, &info.Name)
		if err != nil {
			return nil
		}
		list = append(list, info)
	}
	return list
}
func (d *DB) GetUserName(uid int) string {
	userInfo, err := d.GetUserInfo(uid)
	if err != nil {
		return ""
	}
	name := userInfo["name"].(string)
	return name
}
func Exec(conn *mysql.DB, exec string, tableName string, fileds []string, vals []interface{}) (int, error) {
	code := 0
	if conn == nil {
		return code, errors.New("database conn is empty")
	}
	if tableName == "" || len(fileds) == 0 || len(vals) == 0 || len(fileds) != len(vals) {
		return code, errors.New("params error")
	}
	if exec == "insert" {
		sql := "INSERT INTO " + tableName + "(" + strings.Join(fileds, ",") + ")VALUES(" + ChangeSqlArr(fileds) + ")"
		rows, err := conn.Exec(sql, vals...)
		if err != nil {
			return code, err
		}
		id, err := rows.LastInsertId()
		if err != nil {
			return code, err
		}
		return int(id), nil
	}
	return code, nil
}
